import router from "./router";
import store from "./store";
import { Message } from "element-ui";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { getToken } from "@/utils/auth"; // get token from cookie
import getPageTitle from "@/utils/get-page-title";

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ["/login", "/register-user", "/find-password", "/login-loading"]; // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // console.log(store.state.permission._axiosPromiseArr)
  store.state.permission._axiosPromiseArr.forEach((ele, index) => {
    // ele.cancel("跳转页面,结束请求") // 路由跳转之前，清空（终止）上一个页面正在请求的内容
  })
  store.commit('permission/clear_AxiosPromiseArr')
  // start progress bar
  NProgress.start();

  // set page title
  document.title = getPageTitle(to.meta.title);
  const hasToken = getToken("token");
  const hasAccount = getToken("userInfo");
  // const hasAccount = store.state.user.userInfo.account.length;
  if (hasToken && hasAccount) {
    // 跳转的页面是否为登录页面
    if (to.path === "/login") {
      // if has logged in, redirect select farmlist
      next({ path: "/" });
      NProgress.done();
    } // TODO:king
    else if (to.path === "/edit-password") {
      next();
    }else {
      // 可以判断是否更改过用户信息 比如更改该用户的权限路由
      // 默认为1,刷新时状态初始化1，登录状态改变2，选择农场后状态改变3
      const userStatus = store.getters.status;
      if (userStatus === true || to.path === "/choose-company") {
        next();
      } else {
        try {
          // 路由完成加载后如果检测到没有基地ID 则跳转到选择公司页面
          const hasBaseId = getToken("organizationNo");
          if (!hasBaseId) {
            // if (to.path !== "/choose-company") {
            // console.log(to.path)
            Message.error("检测到基地身份信息过期，请重新选择基地");
            // }
            next({ path: "/" });
          } else {
            store.commit("user/SET_STATUS", true);
            let accessRoutes
            // 请求路由
            accessRoutes = await store.dispatch(
              "permission/generateRoutes"
            );
            router.addRoutes(accessRoutes);
            next({ ...to, replace: true });
          }
        } catch (error) {
          await store.dispatch("user/resetToken");
          Message.error(error || "Has Error");
          next(`/login?redirect=${to.path}`);
          NProgress.done();
        }
      }
    }
  } else {
    /* has no token*/
    /**
   * @description: 无登录升注释
   */
    // console.log(typeof to.path, to.path, whiteList.indexOf(to.path))
    if (whiteList.indexOf(to.path) !== -1) {
    // alert("在白名单中")
    // in the free login whitelist, go directly
      next();
    } else {
      Message.warning("登录已过期,请重新登录");
      // other pages that do not have permission to access are redirected to the login page.
      // next(`/login?redirect=${to.path}`);
      next(`/login`);
      NProgress.done();
    }
  }
});

router.afterEach((to) => {
  // finish progress bar
  NProgress.done();
  // console.log(to)
  // 多页控制 打开新的页面
  store.dispatch('page/open', to)
});
